<template>
  <div class="rolesManagement">
    <h3>角色管理</h3>
    <div class="opration">
      <el-button type="success" icon="el-icon-plus" @click="addData" v-if="isShowAddBtn">新增</el-button>
    </div>
    <div class="list">
      <el-table
        border
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column type="index" width="50" header-align="center" align="center" label="序号"></el-table-column>
        <el-table-column header-align="center" align="center" prop="id" label="角色id" width="90"></el-table-column>
        <el-table-column header-align="center" align="center" prop="name" label="角色名字" width="200"></el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="permissionsString"
          label="权限资源id集合"
        ></el-table-column>
        <el-table-column header-align="center" align="center" prop="squad" label="排序" width="100"></el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          prop="created_at"
          label="创建时间"
          sortable
          width="200"
        ></el-table-column>
        <el-table-column header-align="center" align="center" label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="isShowEditorBtn"
            >编辑</el-button>
            <el-button
              size="mini"
              type="success"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="isShowDeleteBtn"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage1"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalSize"
      ></el-pagination>
    </div>
    <!-- //修改角色信息弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="modifyEditorDialogVisible" width="40%" center>
      <div class="row" v-if="isShowId">
        <span>角色id：</span>
        <el-input v-model="inputRolesId" placeholder clearable :disabled="true"></el-input>
      </div>
      <div class="row">
        <span>角色名称：</span>
        <el-input v-model="inputRolesName" placeholder="请输入角色名称" clearable></el-input>
      </div>
      <div class="row">
        <span>权限资源id集合：</span>
        <!-- <el-select v-model="inputPromissionId" multiple placeholder="请选择" value-key="value">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item"
          ></el-option>
        </el-select>-->
        <div class="checkList">
          <div class="allSelect">
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          </div>
          <div class="selectItem" v-for="(item,index) in permissionDataList" :key="index">
            <div class="checkBoxSelecte">
              <el-checkbox
                v-model="item.checkBox"
                @change="handleCheckBoxChange(item,index)"
              >{{item.name}}</el-checkbox>
            </div>
            <div class="checkGroup">
              <el-checkbox
                @change="handleCheckedPermissionChange(item,index,it,idx)"
                v-model="it.checkedItem"
                v-for="(it,idx ) in item.cellList"
                :label="it.id"
                :key="idx"
              >{{it.name}}</el-checkbox>
            </div>
          </div>
        </div>
      </div>
      <div class="row">
        <span>排序：</span>
        <el-input v-model="inputSort" placeholder="请输入排序" clearable type="number"></el-input>
      </div>
      <div class="dialogBtn">
        <el-button type="primary" size="small" @click="submitModifyEditor">提交</el-button>
        <el-button type="info" size="small" @click="cancelModifyEditor">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "rolesManagement",
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
          num: 1,
          userName: "aaa",
          group: "客服人员",
          type: "普通管理员",
          note: "大师傅艰苦是否就是",
          state: "正常"
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
          num: 2,
          userName: "aaa",
          group: "客服人员",
          type: "普通管理员",
          note: "大师傅艰苦是否就是",
          state: "正常"
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
          num: 3,
          userName: "aaa",
          group: "客服人员",
          type: "普通管理员",
          note: "大师傅艰苦是否就是",
          state: "正常"
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
          num: 4,
          userName: "aaa",
          group: "客服人员",
          type: "普通管理员",
          note: "大师傅艰苦是否就是",
          state: "正常"
        }
      ],
      currentPage1: 1,
      pageSize: 10,
      totalSize: 0,
      //弹窗下拉框选项
      options: [],
      dialogTitle: "修改角色信息",
      modifyEditorDialogVisible: false,
      isShowId: true,
      //弹窗角色id
      inputRolesId: "",
      //弹窗角色名称
      inputRolesName: "",
      //弹窗权限资源id集合
      inputPromissionIds: [],
      //弹窗排序
      inputSort: "",
      //初始化表格数据
      initData: {},
      //根据账号权限判断是否显示添加按钮
      isShowAddBtn: false,
      //根据账号权限判断是否显示编辑按钮
      isShowEditorBtn: false,
      //根据账号权限判断是否显示删除按钮
      isShowDeleteBtn: false,
      //所有权限列表
      permissionDataList: [],
      //全选
      checkAll: false,
      isIndeterminate: true
    };
  },
  mounted() {
    //判断权限
    let permissions = this.$store.state.permissions;
    permissions.forEach((item, index) => {
      if (item == -1 || item == 39) {
        this.isShowEditorBtn = true;
      }
      if (item == -1 || item == 40) {
        this.isShowDeleteBtn = true;
      }
      if (item == -1 || item == 38) {
        this.isShowAddBtn = true;
      }
    });
    this.getDataList();
    this.getPermissionsList();
  },
  methods: {
    //获取初始化数据列表
    async getDataList() {
      let parames = {
        handshake: "",
        data: {
          page: this.currentPage1,
          page_size: this.pageSize
        }
      };
      let res = await this.$axios.post(
        this.$api.roleLists,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.initData = res.data;
        this.initData.data.forEach((item, inedx) => {
          item.permissionsString = item.permissions.join(",");
        });
        this.totalSize = this.initData.total;
        this.tableData = this.initData.data;
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    // 分页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage1 = val;
      this.getDataList();
    },
    //新增
    addData() {
      this.modifyEditorDialogVisible = true;
      this.dialogTitle = "创建角色信息";
      this.isShowId = false;
      this.inputRolesName = "";
      this.inputPromissionId = "";
      this.inputSort = "";
      this.checkAll = false;
      this.permissionDataList.forEach((item, index) => {
        item.checkBox = false;
        item.cellList.forEach((it, idx) => {
          it.checkedItem = false;
        });
      });
    },
    //编辑
    handleEdit(index, row) {
      this.modifyEditorDialogVisible = true;
      this.dialogTitle = "修改角色信息";
      this.isShowId = true;
      this.inputRolesId = row.id;
      this.inputRolesName = row.name;
      this.inputSort = row.squad;
      
      this.checkAll = false;
      this.permissionDataList.forEach((item, index) => {
        item.checkBox = false;
        item.cellList.forEach((it, idx) => {
          it.checkedItem = false;
        });
      });
      //多选框默认选中
      let onoff = false;
      row.permissions.forEach((it, idx) => {
        if (it == -1) {
          onoff = true;
        }
      });
      if (onoff) {
        this.checkAll = true;
        this.permissionDataList.forEach((item, index) => {
          item.checkBox = true;
          item.cellList.forEach((it, idx) => {
            it.checkedItem = true;
          });
        });
      } else {
       
        this.permissionDataList.forEach((item, index) => {
          item.cellList.forEach((it, idx) => {
            row.permissions.forEach((em, ex) => {
              if (it.id == em) {
                it.checkedItem = true;
                  this.$forceUpdate();
              }
            });
          });
        });
      }
      this.permissionDataList.forEach((item, index) => {
        let flag = true;
        item.cellList.forEach((it, idx) => {
          if(!it.checkedItem){
            flag=false;
          };
        });
        if(flag){
          item.checkBox=true;
        }else{
          item.checkBox=false;
        };
      });
      
    },
    //删除
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该行数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteMethod(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //删除接口
    async deleteMethod(_id) {
      let parames = {
        handshake: "",
        data: {
          id: _id
        }
      };
      let res = await this.$axios.post(
        this.$api.roleDelete,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: "删除成功!",
          type: "success"
        });
        this.getDataList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //提交编辑或者新增
    submitModifyEditor() {
      if (this.dialogTitle == "修改角色信息") {
        this.modifyRoles();
      } else {
        this.addRoles();
      }
    },
    //取消提交
    cancelModifyEditor() {
      this.modifyEditorDialogVisible = false;
    },
    //获取所有权限列表
    async getPermissionsList(index, row) {
      let parames = {
        handshake: "",
        data: {}
      };
      let res = await this.$axios.post(
        this.$api.permissionAllTree,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        let allData = res.data;
        Object.keys(allData).forEach(key => {
          let cellList = [];
          Object.keys(allData[key].cell).forEach(ky => {
            allData[key].cell[ky].checkedItem = false;
            cellList.push(allData[key].cell[ky]);
          });
          allData[key].cellList = cellList;
          allData[key].checkBox = false;
          allData[key].checkedItemList = [];
          this.permissionDataList.push(allData[key]);
        });
        console.log(this.permissionDataList);
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //添加角色
    async addRoles() {
      //多选框选择的id集合
      this.inputPromissionIds = [];
      if (this.checkAll) {
        this.inputPromissionIds.push(-1);
      } else {
        this.permissionDataList.forEach((item, index) => {
          item.cellList.forEach((it, idx) => {
            if (it.checkedItem) {
              this.inputPromissionIds.push(it.id);
            }
          });
        });
      }
      if (!this.inputRolesName) {
        this.$message({
          message: "角色名称不能为空!",
          type: "warning"
        });
        return;
      }
      if (this.inputPromissionIds.length < 1) {
        this.$message({
          message: "请选择权限",
          type: "warning"
        });
        return;
      }
      let parames = {
        handshake: "",
        data: {
          name: this.inputRolesName,
          permissions: this.inputPromissionIds,
          squad: this.inputSort
        }
      };
      let res = await this.$axios.post(
        this.$api.roleAdd,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: "添加成功!",
          type: "success"
        });
        this.modifyEditorDialogVisible = false;
        this.getDataList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //修改角色
    async modifyRoles() {
      //多选框选择的id集合
      this.inputPromissionIds = [];
      if (this.checkAll) {
        this.inputPromissionIds.push(-1);
      } else {
        this.permissionDataList.forEach((item, index) => {
          item.cellList.forEach((it, idx) => {
            if (it.checkedItem) {
              this.inputPromissionIds.push(it.id);
            }
          });
        });
      }
      if (!this.inputRolesName) {
        this.$message({
          message: "角色名称不能为空!",
          type: "warning"
        });
        return;
      }
      if (this.inputPromissionIds.length < 1) {
        this.$message({
          message: "请选择权限",
          type: "warning"
        });
        return;
      }
      let parames = {
        handshake: "",
        data: {
          id: this.inputRolesId,
          name: this.inputRolesName,
          permissions: this.inputPromissionIds,
          squad: this.inputSort
        }
      };
      let res = await this.$axios.post(
        this.$api.roleModify,
        JSON.stringify(parames)
      );
      if (res.code == 200) {
        this.$message({
          message: "修改成功!",
          type: "success"
        });
        this.modifyEditorDialogVisible = false;
        this.getDataList();
      } else {
        this.$message({
          message: res.message,
          type: "warning"
        });
      }
    },
    //全选
    handleCheckAllChange() {
      if (this.checkAll) {
        this.permissionDataList.forEach((it, idx) => {
          it.checkBox = true;
          it.cellList.forEach((em, ex) => {
            em.checkedItem = true;
          });
        });
      } else {
        this.permissionDataList.forEach((it, idx) => {
          it.checkBox = false;
          it.cellList.forEach((em, ex) => {
            em.checkedItem = false;
          });
        });
      }
    },
    //单个类型全选
    handleCheckBoxChange(item, index) {
      if (item.checkBox) {
        this.permissionDataList[index].cellList.forEach((it, idx) => {
          it.checkedItem = true;
        });
      } else {
        this.permissionDataList[index].cellList.forEach((it, idx) => {
          it.checkedItem = false;
        });
      }
      let onoff = true;
      this.permissionDataList.forEach((it, idx) => {
        if (!it.checkBox) {
          onoff = false;
        }
      });
      if (onoff) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    },
    //单个类型多选组
    handleCheckedPermissionChange(item, index, id, idx) {
      let onoff = true;
      item.cellList.forEach((em, ex) => {
        if (!em.checkedItem) {
          onoff = false;
        }
      });
      if (onoff) {
        this.permissionDataList[index].checkBox = true;
      } else {
        this.permissionDataList[index].checkBox = false;
      }

      let flag = true;
      this.permissionDataList.forEach((it, idx) => {
        if (!it.checkBox) {
          flag = false;
        }
      });
      if (flag) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    }
  }
};
</script>
<style scoped>
h3 {
  padding: 0.2rem;
  color: #3c763d;
}
.search {
  display: flex;
  margin-top: 0.2rem;
  padding-left: 0.2rem;
  width: 100%;
  flex-wrap: wrap;
}
.el-input {
  width: 80%;
}
.search label {
  width: 0.83rem;
  height: 0.4rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
  border: 1px solid #dcdfe6;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  font-size: 14px;
}
.cond {
  display: flex;
  margin-right: 0.4rem;
  margin-bottom: 0.1rem;
}
.search .el-select >>> .el-input__inner {
  border-left: none;
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
.search .el-select {
  width: 1.67rem;
}
.opration {
  margin-top: 0.2rem;
  padding-left: 0.2rem;
}
.page {
  margin-top: 0.2rem;
  display: flex;
  justify-content: center;
}
.list {
  margin-top: 0.2rem;
  padding: 0 0.1rem;
  font-size: 0.12rem;
}
.dialogBtn {
  display: flex;
  justify-content: center;
  margin-top: 0.3rem;
}
.row {
  margin-bottom: 0.1rem;
  display: flex;
  align-items: center;
}
.row span {
  width: 1rem;
  display: block;
}
.el-select {
  width: 80%;
}
.allSelect {
  margin-bottom: 0.1rem;
}
.checkList {
  width: 80%;
}
.selectItem {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 0.1rem;
}
.checkBoxSelecte {
  width: 1rem;
  /* margin-right: 0.1rem; */
  display: block;
}
.checkGroup {
  width: 80%;
}
</style>